package com.banfeiguanli.springboot.service;

import com.banfeiguanli.springboot.common.Constant;
import com.banfeiguanli.springboot.common.Result;
import com.banfeiguanli.springboot.entity.ClassInfo;
import com.banfeiguanli.springboot.entity.User;
import com.banfeiguanli.springboot.entity.dto.ClassDTO;
import com.banfeiguanli.springboot.exception.ServiceException;
import com.banfeiguanli.springboot.mapper.ClassMapper;
import com.banfeiguanli.springboot.mapper.UserMapper;
import com.banfeiguanli.springboot.utils.TokenUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ClassService {
    @Autowired//注入类
    private ClassMapper classMapper;
    @Autowired//注入类
    private UserMapper userMapper;
    @Autowired//注入类
    private UserService userService;

    //查看所有班级
    public Result findAll(int pageNumber, int pageSize, String searchClass) {
        Map<String, Object> data = new HashMap<>();
        int classTotalNumber = 0;
        List<ClassInfo> classInfos = null;
        pageNumber = (pageNumber - 1) * pageSize;
        classInfos = classMapper.findAll(pageNumber, pageSize, searchClass);
        if (classInfos.isEmpty()) {
            return Result.error(Constant.CODE_510, "暂无班级！");
        }
        classTotalNumber = getTotalNumber(searchClass);
        data.put("classTotal", classTotalNumber);
        data.put("classData", classInfos);
        return Result.success(data);
    }

    public Integer getTotalNumber(String searchClass) {
        return classMapper.getTotalNumber(searchClass);
    }

    public Result createClass(String className, String token) {
        Integer userID = 0, insertNum = -1, classID = 0;
        Map<String, Object> data = new HashMap<>();
        if (className.trim().equals("")) {
            return Result.error();
        }
        userID = TokenUtils.getIdByToken(token);
        //是否加入班级，加入班级就不可以创建班级
        if (isIntoClass(userID)) {
            return Result.error(Constant.CODE_701, "已加入班级，无法创建");
        }
        if (classExistByClassName(className)) {
            return Result.error(Constant.CODE_701, "班级已存在");
        }
        insertNum = classMapper.createClass(className);
        if (insertNum != 1) {
            return Result.error();
        }
        classID = classMapper.getClassIdByClassName(className);
        //更新用户班级ID
        classMapper.updateUserClass(classID, userID);
        if (classID <= 0) {
            return Result.error();
        }
        insertNum = classMapper.insertClassAdmin(userID, classID);
        //班级创建成功，但管理员与班级未绑定
        if (insertNum != 1) {
            return Result.error();
        }
        List<ClassInfo> createdClass = classMapper.getCreatedClass(classID);
        data.put("createdClass", createdClass);
        return Result.success("创建成功", data);
    }

    private boolean classExistByClassName(String className) {
        return !classMapper.classExistByClassName(className).isEmpty();
    }

    private boolean classExistByClassID(int classID) {
        return !classMapper.classExistByClassID(classID).isEmpty();
    }

    public boolean isIntoClass(int userId) {
        return !classMapper.isIntoClass(userId).isEmpty();
    }
    //用户加入班级
    public Result joinClass(ClassDTO classDTO) {
        //从token中取出userId
        int userID = TokenUtils.getIdByToken(classDTO.getUserToken());
        //判断用户是否已经加入班级
        if (isIntoClass(userID)) {
            return Result.error(Constant.CODE_613, "已加入班级，无需再次加入！");
        }
        //
        int classID = classDTO.getClassID();
        if (!classExistByClassID(classID)) {
            throw new ServiceException(Constant.CODE_610, "班级不存在");
        }
        Integer changeRow = classMapper.joinClass(userID, classID);
        if (changeRow == 1) {
            //更新班级人数
            classMapper.updateClassSize(classID);
            //
            return Result.success("加入班级成功", changeRow);
        }
        return Result.error(Constant.CODE_611, "加入班级失败");
    }
    //用户退出班级
    public Result quitClass(ClassDTO classDTO) {
        //从token中取出userId
        int userID = TokenUtils.getIdByToken(classDTO.getUserToken());
        //班级ID
        int classID = classMapper.getClassInfo(userID).getClassID();
        //
        Integer changeRow = classMapper.quitClass(userID);
        if (changeRow == 1) {
            //更新班级人数
            classMapper.updateClassSize(classID);
            //
            return Result.success("退出班级成功", changeRow);
        }
        return Result.error(Constant.CODE_611, "退出班级失败");
    }

    //解散班级
    public Result disMissClass(ClassDTO classDTO) {
        //从token中取出userId
        int userID = TokenUtils.getIdByToken(classDTO.getUserToken());
        //判断用户是否是班级管理员
        if (!userService.userIsClassAdmin(userID)){
            return Result.error(Constant.CODE_620, "非班级管理员，无法解散班级!");
        }
        //获取班级信息
        ClassInfo classInfo = userMapper.getUserClassInfo(userID).get(0);
        //通过用户ID获取班级ID进行对比是否一致
        Integer classID = classInfo.getClassID();
        if (classID != classDTO.getClassID()){
            return Result.error(Constant.CODE_621, "无权解散其他班级!");
        }
        //班费余额大于1禁止解散
        if (classInfo.getClassExBala() > 1) {
            return Result.error(Constant.CODE_623, "班费余额大于1禁止解散");
        }
        //解散班级
        Integer changeRow = 0;
        //移除班级公告
        changeRow = classMapper.removeClassNotice(classID);
        //移除缴费记录
        changeRow = classMapper.removePaymentRecord(classID);
        //移除缴费项目
        changeRow = classMapper.removePaymentProject(classID);
        //移除班级管理员
        changeRow = classMapper.removeClassAdmin(classID);
        if (changeRow < 1) {
            return Result.error(Constant.CODE_624, "移除班级管理员失败！");
        }
        //移除班级成员
        changeRow = classMapper.removeClassUser(classID);
        if (changeRow < 1) {
            return Result.error(Constant.CODE_625, "移除班级成员失败！");
        }
        //删除班级
        changeRow = classMapper.removeClass(classID);
        if (changeRow != 1) {
            return Result.error(Constant.CODE_622, "删除班级失败！");
        }
        return Result.success( "解散班级成功！");
    }

    //获取班级成员
    public Result getClassUserList(String token, int pageNumber, int pageSize, String searchUser) {
        Map<String, Object> data = new HashMap<>();
        int userID = TokenUtils.getIdByToken(token);
        //判断是否加入班级
        if (!isIntoClass(userID)){
            return Result.error(Constant.CODE_612, "未加入班级！");
        }
        //非班级管理员
        if (!userService.userIsClassAdmin(userID)){
            return Result.error(Constant.CODE_620, "权限不足！");
        }
        //获取班级成员
        pageNumber = (pageNumber - 1) * pageSize;
        List<User> classUserList = classMapper.getClassUserList(userID, pageNumber, pageSize, searchUser);
        //
        int classSize = classMapper.getClassSize(userID, searchUser);
        //
        data.put("classSize", classSize);
        data.put("classUserList", classUserList);
        return Result.success(data);
    }

    //移除班级成员
    public Result removeUser(ClassDTO classDTO) {
        Map<String, Object> data = new HashMap<>();
        //管理员token
        String token = classDTO.getUserToken();
        int adminUserID = TokenUtils.getIdByToken(token);
        int removeUserID = classDTO.getUserID();
        //判断二者ID是否相同
        if (adminUserID == removeUserID){
            return Result.error(Constant.CODE_631, "管理员无法移除自己!");
        }
        //判断是否加入班级
        if (!isIntoClass(adminUserID)){
            return Result.error(Constant.CODE_612, "未加入班级！");
        }
        //非班级管理员
        if (!userService.userIsClassAdmin(adminUserID)){
            return Result.error(Constant.CODE_620, "权限不足！");
        }
        //获取班级管理员的班级ID
        int adminUserClassID = classMapper.getClassInfo(adminUserID).getClassID();
        //获取被移除用户的班级ID
        int removeUserClassID = classMapper.getClassInfo(removeUserID).getClassID();
        //判断二者的班级ID是否相同
        if (adminUserClassID != removeUserClassID) {
            return Result.error(Constant.CODE_630, "无权移除其他班级的成员!");
        }
        //
        Integer changeRow = classMapper.removeUser(removeUserID);
        //更新班级人数
        classMapper.updateClassSize(adminUserClassID);
        //
        data.put("removeUserTotal", changeRow);
        return Result.success(data);
    }

    //获取班级信息(后台管理)
    public Result getClassInfoForBack(String token, Integer pageNumber, Integer pageSize, String searchClass) {
        Map<String, Object> data = new HashMap<>();
        //提取adminID
        Integer adminID = TokenUtils.getIdByToken(token);
        //查询信息
        pageNumber = (pageNumber - 1) * pageSize;
        List<ClassInfo> classInfo = classMapper.getClassInfoForBack(pageNumber, pageSize, searchClass);
        data.put("classInfo", classInfo);
        //统计总数
        Integer classTotal = classMapper.countClassTotal(searchClass);
        data.put("classTotal", classTotal);
        return Result.success(data);
    }

    //禁封班级
    public Result banClass(ClassDTO classDTO) {
        Integer updateRow = classMapper.banClass(classDTO);
        if (updateRow != 1) {
            return Result.error("禁封失败！");
        }
        return Result.success("禁封成功！", null);
    }

    //解封班级
    public Result unBanClass(ClassDTO classDTO) {
        Integer updateRow = classMapper.unBanClass(classDTO);
        if (updateRow != 1) {
            return Result.error("解封失败！");
        }
        return Result.success("解封成功！", null);
    }

    //检测班级是否被禁封
    public List<ClassInfo> getClassInfo(Integer userID) {
        return classMapper.getClassInfoForCheck(userID);
    }
}
